﻿
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Windows.Data;
using System.Text;

namespace Red.Controls.Converters 
{
    public class PropertyNameConverter : IValueConverter
    {
        public object Convert( object value, Type targetType, object parameter, CultureInfo culture )
        {
            string name = (string)value;
            return SplitIntoWords( name );
        }

        public object ConvertBack( object value, Type targetType, object parameter, CultureInfo culture )
        {
            throw new NotImplementedException();
        }

        private string SplitIntoWords( string name )
        {
            if ( String.IsNullOrEmpty( name ) )
            {
                return String.Empty;
            }

            bool isQuestion = // detecting 'isSomething' names
                name.Length >= 3 && Char.ToLower( name[ 0 ] ) == 'i' && name[ 1 ] == 's' && 
                ( name[ 2 ] == ' ' || Char.IsUpper( name[ 2 ] ) );

            var result = new StringBuilder();
            int startIdx = isQuestion ? 2 : 0;
            result.Append( Char.ToUpper( name[ startIdx ] ) );
            for ( int i = startIdx + 1; i < name.Length; ++i )
            {
                if ( Char.IsUpper( name[ i ] ) && i != name.Length - 1 
                    && !Char.IsSeparator( name[ i + 1 ] ) 
                    && Char.IsLower( name[ i + 1 ] ) )
                {
                    result.Append( ' ' );
                    result.Append( Char.ToLower( name[ i ] ) );
                }
                else
                {
                    result.Append( name[ i ] );
                }
            }

            if ( isQuestion )
            {
                result.Append( '?' );
            }

            return result.ToString();
        }
    }
}
